import {messages} from "share/common";
/**
 * Created by Allen on 2018/1/31.
 */
import React from 'react'
import ReactDOM from 'react-dom'
import { connect } from 'react-redux'
import { Form, Input, DatePicker, Switch, Icon, Button, Select, Spin, Alert, Checkbox, Table, Popover } from 'antd'
import moment from 'moment';
import 'styles/my-agency/new-agent.scss'
import myAgencyService from 'containers/my-agency/my-agency.service'
const FormItem = Form.Item;
const Option = Select.Option;
const CheckboxGroup = Checkbox.Group;

class NewAgent extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      data: [],
      status: '',
      record: null,
      disabled: true,
      fetching: false,
      applyFold: true,
      showAlert: false,    //选中要离职的人员时slide上方的提示
      expenseFold: true,
      endDate: false,  //是否有结束日期
      showExpenseFold: false,
      showApplicationFold: false,
      principalValidateStatus: '',  //被代理人校验
      principalHelp: '', //被代理人校验内容
      columnsRequest: [
        {title: messages('my-agency.key19'/*申请单名称*/), dataIndex: 'formName', render: (value, record) => (
          <Popover content={value}>{value}{record.valid ? '' : '(' + messages('my-agency.key20'/*已停用*/) + ')'}</Popover>
        ) || '-'},
        {title: messages('my-agency.key21'/*公司*/), dataIndex: 'companyName', render: value => (
          <Popover content={value}>{value}</Popover>
        ) || '-'}
      ],
      columnsExpense: [
        {title: messages('my-agency.key22'/*报销单名称*/), dataIndex: 'formName', render: (value, record) => (
          <Popover content={value}>{value}{record.valid ? '' : '(' + messages('my-agency.key20'/*已停用*/) + ')'}</Popover>
        ) || '-'},
        {title: messages('my-agency.key21'/*公司*/), dataIndex: 'companyName', render: value => (
          <Popover content={value}>{value}</Popover>
        ) || '-'}
      ],
      columnsLoan: [
        {title: messages('my-agency.key48')/*借款单名称*/, dataIndex: 'formName', render: (value, record) => (
          <Popover content={value}>{value}{record.valid ? '' : '(' + messages('my-agency.key20'/*已停用*/) + ')'}</Popover>
        ) || '-'},
        {title: messages('my-agency.key21'/*公司*/), dataIndex: 'companyName', render: value => (
          <Popover content={value}>{value}</Popover>
        ) || '-'}
      ],
      dataRequest: [],
      dataExpense: [],
      dataLoan: [],
      requestBills: [], //所有的申请单据
      expenseBills: [], //所有的费用单据
      loanBills: [], //所有的借款单据
      hideStatusItem: true, //隐藏状态开关
    };
  }

  componentDidMount() {}

  componentWillReceiveProps(nextProps) {
    if (nextProps.params.record && this.state.record !== nextProps.params.record){  //编辑
      this.setState({
        record: nextProps.params.record,
        showApplicationFold: false,
        status: nextProps.status,
        showExpenseFold: false,
        expenseFold: true,
        applyFold: true
      },() => {
        this.getAgentBills(nextProps.params.billOptions);
        if (this.state.record.endDate){
          this.setState({endDate: true})
        }else {
          this.setState({endDate: false})
        }
      });
    } else if (!nextProps.params.record){                      //新建
      this.setState({record: null});
    }
  }

  getAgentBills = (billOptions) => {
    const { record } = this.state;
    let requestBills = JSON.parse(JSON.stringify(billOptions)).requestBills;
    let expenseBills = JSON.parse(JSON.stringify(billOptions)).expenseBills;
    let loanBills = JSON.parse(JSON.stringify(billOptions)).loanBills;
    let dataRequest = [];
    let dataExpense = [];
    let dataLoan = [];
    record && record.customFormDTOs.map(item => {
      if (item.entityType === 1001) { //申请单
        requestBills.map(bill => {
          item.formOID === bill.formOID && dataRequest.push(bill);
        })
      }
      if (item.entityType === 1002) { //报销单
        expenseBills.map(bill => {
          item.formOID === bill.formOID && dataExpense.push(bill);
        })
      }
      if (item.entityType === 3001) { //借款单
        loanBills.map(bill => {
          item.formOID === bill.formOID && dataLoan.push(bill);
        })
      }
    });
    this.setState({ dataRequest, dataExpense, dataLoan });
  };

  onCancel =() =>{
    this.props.close()
  };

  render(){

    const { getFieldDecorator } = this.props.form;
    const { record, status, data, columnsRequest, columnsExpense, columnsLoan, dataRequest, dataExpense, dataLoan, hideStatusItem } = this.state;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 10, offset: 1}
    };
    const options = data.map(d => <Option key={JSON.stringify(d)}>{d.text}</Option>);
    return (
      <div className="new-agent">
        <Form onSubmit={this.handleSave}>
          {/*task#41098 我的代理 - 新建代理 - 状态按钮前端隐藏*/}
          {!hideStatusItem && (
            <FormItem {...formItemLayout} label={messages('common.column.status')}> {/*状态*/}
            {getFieldDecorator('enabled',{
              initialValue: record ? record.enabled : true,
              valuePropName: 'checked'
            })(
              <Switch checkedChildren={<Icon type="check"/>}
                      unCheckedChildren={<Icon type="cross"/>} disabled/>
            )}
          </FormItem>)}
          <FormItem {...formItemLayout}
                    label={status === 'AGENT' ? messages('my-agency.key23'/*代理人*/) : messages('my-agency.key24'/*授权人*/)}> {/*代理人*/}
            {getFieldDecorator('record.principalUserDTO.fullName',{
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: record ? (status === 'AGENT' ? record.proxyUserDTO.fullName : record.principalUserDTO.fullName) : ''
            })(
              <Select disabled>
                {options}
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('my-agency.key25'/*开始日期*/)}> {/*开始日期*/}
            {getFieldDecorator('record.startDate',{
              rules: [{
                required: true
              }],
              initialValue: record ? moment(record.startDate) : moment(new Date())
            })(
              <DatePicker disabled/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('my-agency.key26'/*结束日期*/)}> {/*结束日期*/}
            {getFieldDecorator('record.endDate',{
              initialValue:  record && record.endDate ? moment(record.endDate) : null
            })(
              <DatePicker placeholder="无限制" disabled/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('my-agency.key6'/*代理单据*/)}>
            {getFieldDecorator('record.customFormDTOs')(
              <div className="agent-bills">
                {record && record.proxyFormScope === 1001 && (
                  <div>{messages('common.all')}</div>
                )}
                {record && record.proxyFormScope === 1002 && (
                  <div>
                    <div className="expense-bills">
                      <div className="table-header">
                        <div className="table-header-title">
                          【{messages('my-agency.key27'/*报销单*/)}】
                          {messages('common.total1', {total: dataExpense.length})}
                        </div>
                      </div>
                      <Table columns={columnsExpense}
                             dataSource={dataExpense}
                             bordered
                             pagination={{pageSize: 5}}
                             size="middle"
                             rowKey="formOID"/>
                    </div>
                    <div className="request-bills">
                      <div className="table-header">
                        <div className="table-header-title">
                          【{messages('my-agency.key28'/*申请单*/)}】
                          {messages('common.total1', {total: dataRequest.length})}
                        </div>
                      </div>
                      <Table columns={columnsRequest}
                             dataSource={dataRequest}
                             bordered
                             pagination={{pageSize: 5}}
                             size="middle"
                             rowKey="formOID"/>
                    </div>
                    <div className="loan-bills">
                      <div className="table-header">
                        <div className="table-header-title">
                          【{messages('my-agency.key49')/*借款单*/}】
                          {messages('common.total1', {total: dataLoan.length})}
                        </div>
                      </div>
                      <Table columns={columnsLoan}
                             dataSource={dataLoan}
                             bordered
                             pagination={{pageSize: 5}}
                             size="middle"
                             rowKey="formOID"/>
                    </div>
                  </div>
                )}
              </div>
            )}
          </FormItem>

          <div className="slide-footer">
            <Button onClick={this.onCancel}>{messages('common.back')}</Button>
          </div>
        </Form>
      </div>
    )

  }

}

function mapStateToProps(state) {
  return {}
}

const WrappedNewAgent = Form.create()(NewAgent);

export default connect(mapStateToProps)(WrappedNewAgent)
